// MyOrderPage.js
import strHtml from "./MyOrderPage.html"; // 使用 raw-loader 加载 HTML 文件
import { DomUtils } from "../../utils/DomUtils"; // 引入 DomUtils 类
import { BasePage } from "../BacePage"; // 引入 BacePage 类

export class MyOrderPage extends BasePage {
  constructor() {
    super();
    // 农产品类订单数据，含物流节点
    this.orders = [
      {
        date: "2025-06-01",
        orderNo: "202506011234567890",
        shopName: "vivi",
        productImg: "../../assets/images/xi.jpg",
        productName: "西红柿",
        price: 2.5,
        count: 2,
        totalPrice: 15.0,
        shippingFee: 10.0,
        logisticsNo: "SF1234567892",
        status: "待收货",
        logisticsStatus: 3,
        commentStatus: "未评",
        logistics: [
          { name: "拍下商品", time: "2025-06-01 10:00:00", done: true },
          { name: "付款到支付宝", time: "2025-06-01 10:01:00", done: true },
          { name: "卖家发货", time: "2025-06-01 15:30:00", done: true },
          { name: "确认收货", time: "", done: false },
          { name: "评价", time: "", done: false },
        ],
      },
      {
        date: "2025-06-03",
        orderNo: "202506031234567891",
        shopName: "vivi",
        productImg: "../../assets/images/tudou.jpg",
        productName: "土豆",
        price: 4.0,
        count: 3,
        totalPrice: 22.0,
        shippingFee: 10.0,
        logisticsNo: "SF1234567891",
        status: "success",
        logisticsStatus: 6,
        commentStatus: "已评",
        logistics: [
          { name: "拍下商品", time: "2025-06-03 09:00:00", done: true },
          { name: "付款到支付宝", time: "2025-06-03 09:01:00", done: true },
          { name: "卖家发货", time: "2025-06-03 12:00:00", done: true },
          { name: "确认收货", time: "2025-06-04 05:00:00", done: true },
          { name: "评价", time: "2025-06-05 02:00:00", done: true },
        ],
        comments: [
          {
            userType: "buyer",
            avatar: "../../assets/images/users/user-1.jpg",
            nickname: "kk",
            content: "蔬菜很新鲜，包装也很好！",
            time: "2025-06-05 09:05:00",
          },
        ],
      },
      {
        date: "2025-06-05",
        orderNo: "202505051234567892",
        shopName: "vivi",
        productImg: "../../assets/images/xi.jpg",
        productName: "西红柿",
        price: 2.5,
        count: 5,
        totalPrice: 22.5,
        shippingFee: 20.0,
        status: "待发货",
        logisticsStatus: 0, // 对应"待发货"索引，或者可以不设置表示无物流
        commentStatus: "未评",
        logistics: [
          { name: "拍下商品", time: "2025-06-05 01:00:00", done: true },
          { name: "付款到支付宝", time: "2025-06-05 01:01:00", done: true },
          { name: "卖家发货", time: "", done: false },
          { name: "确认收货", time: "", done: false },
          { name: "评价", time: "", done: false },
        ],
      },
    ];
    this.commentModal = null;
    this.logisticsModal = null;
    this.currentCommentOrderIndex = null;
  }

  render() {
    const dom = DomUtils.convertToDom(strHtml);
    this.dom = dom;
    this._renderOrders();
    this._bindEvents();
    return dom;
  }

  _renderOrders() {
    const container = this.dom.querySelector("#my-order-list");
    container.innerHTML = "";
    const showConfirmBtnStatus = [
      "待发货",
      "已发货",
      "已揽收",
      "运输中",
      "派送中",
      "已签收",
    ];
    this.orders.forEach((order, idx) => {
      const card = document.createElement("div");
      card.className = "order-card mb-4 p-3 border rounded";
      card.innerHTML = `
        <div class="d-flex justify-content-between align-items-center mb-2">
          <div>
            <strong>${order.date}</strong>
            <span class="ms-3 text-muted">订单号：${order.orderNo}</span>
          </div>
          <div>
            <span class="badge bg-primary">${order.shopName}</span>
          </div>
        </div>
        <div class="d-flex align-items-center">
          <img src="${
            order.productImg
          }" class="rounded" style="width: 80px; height: 80px; object-fit: cover;">
          <div class="ms-3 flex-grow-1">
            <div class="fw-bold">${order.productName}</div>
            <div class="text-muted small">￥${order.price.toFixed(2)} × ${
        order.count
      }</div>
          </div>
          <div class="flex-shrink-0 text-center" style="min-width:160px;">
            <div class="fw-bold fs-5">￥${order.totalPrice.toFixed(2)}</div>
            <div class="text-muted small">(含运费: ￥${order.shippingFee.toFixed(
              2
            )})</div>
          </div>
          <div class="flex-shrink-0 text-center" style="min-width:120px;">
            ${
              order.status !== "closed"
                ? `<a href=\"javascript:;\" class=\"d-block small btn-logistics\" data-idx=\"${idx}\">查看物流</a>`
                : ""
            }
            <div>
              ${
                order.status === "success"
                  ? '<span class="text-success small">交易成功</span>'
                  : order.status === "closed"
                  ? '<span class="text-danger small">交易关闭</span>'
                  : ""
              }
            </div>
          </div>
          <div class="flex-shrink-0 text-end" style="min-width:160px;">
            ${
              order.status === "待收货"
                ? `<button class=\"btn btn-outline-success btn-sm btn-confirm-receive\" data-idx=\"${idx}\">确认收货</button>`
                : ""
            }
            ${
              order.status === "待评价"
                ? `<button class=\"btn btn-outline-primary btn-sm btn-comment\" data-idx=\"${idx}\">评价</button>`
                : ""
            }
            ${
              order.status === "已评价"
                ? `<button class=\"btn btn-outline-primary btn-sm mt-2 btn-rebuy\" data-idx=\"${idx}\">再次购买</button>`
                : ""
            }
            ${
              order.status === "success" || order.status === "closed"
                ? `<button class=\"btn btn-outline-primary btn-sm mt-2 btn-rebuy\" data-idx=\"${idx}\">再次购买</button>`
                : ""
            }
            ${
              order.comments &&
              order.comments.some((c) => c.userType === "buyer")
                ? `<a href="javascript:;" class="d-block small mt-2 btn-view-comment px-3 py-1" data-idx=\"${idx}\" style=\"display: inline-block;\">查看评价</a>`
                : ""
            }
          </div>
        </div>
      `;
      container.appendChild(card);
    });
  }

  _renderLogisticsSteps(logistics) {
    let html =
      '<div class="d-flex justify-content-between align-items-center" style="margin:40px 20px 20px 20px">';
    logistics.forEach((step, idx) => {
      // 计算当前步骤是否完成
      const isDone = step.done;
      // 判断下一个步骤是否完成，用于连接线
      const nextStepDone =
        idx < logistics.length - 1 ? logistics[idx + 1].done : false;

      html += `
        <div class="text-center flex-fill" style="position:relative;">
          <div style="font-size:15px;color:${
            isDone ? "#43b244" : "#888"
          };font-weight:${isDone ? "bold" : "normal"};margin-bottom:6px;">${
        step.name
      }</div>
          <div style="z-index:2;position:relative;">
            <div style="
              width:38px;height:38px;
              margin:0 auto 8px auto;
              border-radius:50%;
              background:${isDone ? "#43b244" : "#e0e0e0"};
              color:#fff;display:flex;align-items:center;justify-content:center;
              font-size:22px;
              border:3px solid ${isDone ? "#43b244" : "#e0e0e0"};
              box-shadow:${isDone ? "0 0 8px #43b24455" : "none"};
            ">
              ${
                isDone
                  ? '<svg width="20" height="20" fill="currentColor" viewBox="0 0 16 16"><path d="M13.485 1.929a1.5 1.5 0 0 1 0 2.121l-7.07 7.07a1.5 1.5 0 0 1-2.122 0l-2.12-2.12a1 1 0 1 1 1.415-1.415l2.12 2.12a.5.5 0 0 0 .707 0l7.07-7.07a1.5 1.5 0 0 1 2.12 0z"/></svg>'
                  : idx + 1
              }
            </div>
          </div>
          ${
            idx < logistics.length - 1
              ? `<div style="position:absolute;top:19px;left:50%;width:calc(100% - 40px);height:3px;z-index:1;transform:translateX(-50%);left:20px;right:20px;">
                <div style="height:100%;background:${
                  isDone && nextStepDone ? "#43b244" : "#e0e0e0"
                }"></div>
              </div>`
              : ""
          }
        </div>
      `;
    });
    html += "</div>";
    return html;
  }

  _bindEvents() {
    this.dom.querySelector("#my-order-list").addEventListener("click", (e) => {
      if (e.target.classList.contains("btn-confirm-receive")) {
        const idx = e.target.getAttribute("data-idx");
        this.orders[idx].status = "待评价";
        this._renderOrders();
      }
      if (e.target.classList.contains("btn-comment")) {
        const idx = e.target.getAttribute("data-idx");
        this.currentCommentOrderIndex = idx;
        this.dom.querySelector("#myCommentContent").value = "";
        new bootstrap.Modal(this.dom.querySelector("#myCommentModal")).show();
      }
      if (e.target.classList.contains("btn-logistics")) {
        const idx = e.target.getAttribute("data-idx");
        const order = this.orders[idx];
        const modalEl = this.dom.querySelector("#myLogisticsModal");
        if (modalEl) {
          // 显示物流单号
          const noEl = modalEl.querySelector("#my-logistics-no");
          if (noEl) {
            noEl.innerHTML = `<strong>物流单号：</strong>${
              order.logisticsNo || "暂无"
            }`;
          }
          // 横向进度条
          const stepsContainer = modalEl.querySelector("#my-logistics-steps");
          if (stepsContainer) {
            const steps = [
              "待发货",
              "已发货",
              "已揽收",
              "运输中",
              "派送中",
              "待收货",
              "已签收",
            ];
            // logisticsStatus 表示当前进度索引（0-6），如无可自行补充
            const currentStep = order.logisticsStatus || 0;
            const highlightColor = "#e74c3c"; // 红色
            let html = `
              <div style="position:relative;">
                <div style="
                  position:absolute;
                  top:70%;
                  left:70px; 
                  right:70px;
                  height:6px;
                  background:#e0e0e0;
                  z-index:1;
                  transform:translateY(-50%);
                ">
                  <div style="
                    width:${
                      currentStep > 0
                        ? (currentStep / (steps.length - 1)) * 100
                        : 0
                    }%;
                    height:100%;
                    background:${highlightColor};
                  "></div>
                </div>
                <div class="d-flex justify-content-between align-items-center" style="position:relative;z-index:2;">
            `;
            steps.forEach((step, i) => {
              html += `
                <div class="text-center flex-fill" style="position:relative;">
                  <div style="font-size:15px;color:${
                    i <= currentStep ? highlightColor : "#888"
                  };font-weight:${
                i === currentStep ? "bold" : "normal"
              };margin-bottom:6px;">${step}</div>
                  <div style="
                    width:38px;height:38px;
                    margin:0 auto 0 auto;
                    border-radius:50%;
                    background:${i <= currentStep ? highlightColor : "#e0e0e0"};
                    color:#fff;display:flex;align-items:center;justify-content:center;
                    font-size:22px;
                    border:3px solid ${
                      i <= currentStep ? highlightColor : "#e0e0e0"
                    };
                    box-shadow:${
                      i <= currentStep
                        ? "0 0 8px " + highlightColor + "55"
                        : "none"
                    };
                    position:relative;z-index:2;
                  ">
                    ${
                      i < currentStep
                        ? '<svg width="20" height="20" fill="currentColor" viewBox="0 0 16 16"><path d="M13.485 1.929a1.5 1.5 0 0 1 0 2.121l-7.07 7.07a1.5 1.5 0 0 1-2.122 0l-2.12-2.12a1 1 0 1 1 1.415-1.415l2.12 2.12a.5.5 0 0 0 .707 0l7.07-7.07a1.5 1.5 0 0 1 2.12 0z"/></svg>'
                        : i + 1
                    }
                  </div>
                </div>
              `;
            });
            html += `</div></div>`;
            stepsContainer.innerHTML = html;
          }
          new bootstrap.Modal(modalEl).show();
        }
      }
      if (e.target.classList.contains("btn-view-comment")) {
        const idx = e.target.getAttribute("data-idx");
        this._showViewCommentModal(idx);
      }
    });
    this.dom
      .querySelector("#mySubmitCommentBtn")
      .addEventListener("click", () => {
        const content = this.dom
          .querySelector("#myCommentContent")
          .value.trim();
        if (!content) {
          alert("请输入评价内容");
          return;
        }
        const idx = this.currentCommentOrderIndex;
        this.orders[idx].status = "已评价";
        // 添加买家评价
        this.orders[idx].comments = this.orders[idx].comments || [];
        this.orders[idx].comments.push({
          userType: "buyer",
          avatar: "../../assets/images/users/user-1.jpg",
          nickname: "kk",
          content: content,
          time: new Date().toLocaleString(),
        });
        this._renderOrders();
        const modal = bootstrap.Modal.getInstance(
          this.dom.querySelector("#myCommentModal")
        );
        if (modal) {
          modal.hide();
        }
      });
  }

  // 新增：渲染评价弹窗
  _showViewCommentModal(idx) {
    let modal = document.getElementById("myViewCommentModal");
    if (!modal) {
      modal = document.createElement("div");
      modal.className = "modal fade";
      modal.id = "myViewCommentModal";
      modal.tabIndex = -1;
      modal.innerHTML = `
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">评价详情</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="myViewCommentBody"></div>
          </div>
        </div>
      `;
      document.body.appendChild(modal);
    }
    // 渲染内容
    const order = this.orders[idx];
    const body = modal.querySelector("#myViewCommentBody");
    if (body) {
      if (!order.comments || order.comments.length === 0) {
        body.innerHTML = '<div class="text-center text-muted">暂无评价</div>';
      } else {
        body.innerHTML = order.comments
          .map(
            (c) => `
          <div class="d-flex align-items-start mb-3">
            <img src="${c.avatar}" style="width:40px;height:40px;border-radius:50%;object-fit:cover;">
            <div class="ms-2 flex-grow-1">
              <div><strong>${c.nickname}</strong></div>
              <div class="text-muted small">${c.time}</div>
              <div class="mt-1">${c.content}</div>
            </div>
          </div>
        `
          )
          .join("");
      }
    }
    new bootstrap.Modal(modal).show();
  }
}
